package com.starsoft.trade.job;

import java.util.Date;
import java.util.List;

import org.quartz.JobExecutionContext;

import com.starsoft.frame.base.bean.BaseJobLog;
import com.starsoft.frame.base.job.AbstractJob;
import com.starsoft.frame.util.SpringContext;
import com.starsoft.smdc.bean.SmdcDiv;
import com.starsoft.smdc.service.DivService;
import com.starsoft.smdc.service.HolidayService;
import com.starsoft.trade.bean.TradeAcount;
import com.starsoft.trade.bean.TradeAcountStatus;
import com.starsoft.trade.bean.TradeBill;
import com.starsoft.trade.bean.TradePosition;
import com.starsoft.trade.service.AcountStatusService;
import com.starsoft.trade.service.TradeAcountService;
import com.starsoft.trade.service.TradeBillService;
import com.starsoft.trade.trader.LocalTrader;
import com.starsoft.trade.util.TradeType;

public class AcountDivBillJob extends AbstractJob {

	@Override
	public void run(JobExecutionContext context, BaseJobLog jobLog) {
		HolidayService holidayService = SpringContext.getBean(HolidayService.class);
		TradeAcountService tradeAcountService = SpringContext.getBean(TradeAcountService.class);
		AcountStatusService acountStatusService = SpringContext.getBean(AcountStatusService.class);
		DivService divService = SpringContext.getBean(DivService.class);
		LocalTrader localTrader = SpringContext.getBean(LocalTrader.class);
		TradeBillService billService = SpringContext.getBean(TradeBillService.class);
		
		Date now = new Date();
		Date lastDay = holidayService.getNextBusinessDay(now, -1);
		if(!holidayService.isBusinessDay(now)){
			jobLog.setDesp("不是交易日");
			return;
		}
		List<TradeAcount> tradeAcounts = tradeAcountService.getAll();
		
		
		int divBillCount = 0;
		for (TradeAcount tradeAcount : tradeAcounts) {
			if(!tradeAcountService.isAlive(tradeAcount, new Date())){
				continue;
			}
			Integer acountId = tradeAcount.getAcountId();
			TradeAcountStatus status = acountStatusService.getAcountStatus(acountId, lastDay);
			List<TradePosition> positions = status.getPositions();
			for (TradePosition position : positions) {
				SmdcDiv div = divService.get(position.getId().getSecId(), now);
				if (div == null || position.getSecNum() == 0) {
					continue;
				}
				boolean hasDoneDiv = false;
				List<TradeBill> bills = billService.getBills(acountId, position.getId().getSecId(), now);
				for (TradeBill bill : bills) {
					if (TradeType.get(bill).isDiv()) {
						hasDoneDiv = true;
					}
				}
				if (!hasDoneDiv) {
					TradeBill bill = localTrader.trade(acountId, position, div);
					if (bill != null) {
						billService.saveOrUpdate(bill);
						divBillCount++;
					}
				}
			}
		}
		
		jobLog.setDesp("生成Div Bill: "+divBillCount);
	}

}
